package cn.sc.summer.mybatis.listener;

import cn.sc.summer.mybatis.event.SqlEvent;
import cn.sc.summer.mybatis.po.Sql;
import com.alibaba.fastjson.JSONObject;
import cn.sc.summer.constant.rabbit.RabbitConstant;
import cn.sc.summer.rabbitmq.builder.RabbitBuilder;
import cn.sc.summer.rabbitmq.builder.RabbitMessageBuilderDirector;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 异步监听日志事件
 *
 * @author a-xin
 * @date 2019/3/12 23:59
 */
@Slf4j
@Component
public class SqlListener {

    @Resource
    private RabbitTemplate rabbitTemplate;

    public SqlListener() {
    }

    /**
     * 异步记录sql日志
     *
     * @param event event
     */
    @EventListener(SqlEvent.class)
    public void saveSqlLog(SqlEvent event) {
        Sql sql = (Sql) event.getSource();
        JSONObject message = new RabbitMessageBuilderDirector(new RabbitBuilder()).build();
        message.put(RabbitConstant.MESSAGE_KEY, JSONObject.toJSONString(sql));
        rabbitTemplate.convertAndSend(
                RabbitConstant.SQL_RECORD_EXCHANGE,
                RabbitConstant.SQL_RECORD_ROUTING_KEY,
                message.toJSONString());
    }

}
